﻿// <copyright file="AudioModuleView.xaml.cs" company="Waveform Lab.NET">
// Signal processing by PC oscilloscope
// http://waveformlab.codeplex.com/
//
// Copyright (c) 2011 Waveform Lab.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.IO;
using System.Threading;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using PluginModule.Core;
using MemoryModule;

#if SILVERLIGHT
using AudioModule_SL;
#else
using NAudio.Wave;
using NAudio.CoreAudioApi;
#endif

namespace AudioModule
{
    /// <summary>
    /// Interaction logic for AudioModuleView.xaml
    /// </summary>
    [Export(typeof(IPlugin))]
    [ExportMetadata("ModuleName", "AudioModule")]
    [ExportMetadata("ModuleId", 1)]
    public partial class AudioModueView : UserControl, IPlugin
    {
        private bool _captured = false;
        private bool _enable_left = true;
        private bool _enable_right = true;
        private uint _buffer_no = 0;
        private string _name_x = string.Empty;
        private string _name_y = string.Empty;
        private double _samplerate = 0.0;
        private int _samplenumber = 0;

        public AudioModueView()
        {
            InitializeComponent();

#if !SILVERLIGHT
            if (System.Environment.OSVersion.Version.Major >= 6)
            {
                LoadWasapiDevicesCombo();
                wasapi = true;
            }
            else
            {
                wasapi = false;
            }

            dir = new util();
#endif
        }

        public string ModuleName
        {
            get { return "AudioModule"; }
        }

        public bool Captured
        {
            get { return _captured; }
            set { _captured = value; }
        }

        public bool EnableLeft
        {
            get { return _enable_left; }
        }

        public bool EnableRight
        {
            get { return _enable_right; }
        }

        public uint BufferNo
        {
            get { return _buffer_no; }
        }

        public string FileName
        {
            get { return string.Empty; }
        }

        public string NameX
        {
            get { return string.Empty; }
        }

        public string NameY
        {
            get { return string.Empty; }
        }

        public double SampleRate
        {
            get { return _samplerate; }
        }

        public int SampleNumber
        {
            get { return _samplenumber; }
        }

        public double NyquistRate
        {
            get { return 0.0; }
            set { }
        }

        public int ActualSamplingNumber
        {
            get { return 0; }
            set { }
        }

        private util dir;
#if SILVERLIGHT

#else
        private IWaveIn waveIn;
        private WaveFileWriter writer;
        private bool wasapi = false;
#endif
        private bool trigger_left = false;
        private bool trigger_right = false;
        private int off_cnt_left = 0;
        private int off_cnt_right = 0;
        private float[] mem_l;
        private float[] mem_r;
        private int mem_size = 30000;
        private int filter_index = 0;
        private float noize_reject = 0.1f;
        private int BufferCnt = 100;
        private double axis_x_mux = 1.0;
        double axis_y_mux = 1.0;
        private float left_in = 0.25f;
        private float left_out = 0.1f;
        private float right_in = 0.25f;
        private float right_out = 0.1f;
        private bool run = true;
        private int run_cnt = 0;

#if !SILVERLIGHT
        private void LoadWasapiDevicesCombo()
        {
            MMDeviceEnumerator deviceEnum = new MMDeviceEnumerator();
            MMDeviceCollection deviceCol = deviceEnum.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active);

            Collection<MMDevice> devices = new Collection<MMDevice>();

            foreach (MMDevice device in deviceCol)
            {
                devices.Add(device);
            }

            this.comboDevices.ItemsSource = devices;
            if (comboDevices.Items.Count >= 1) comboDevices.SelectedIndex = 0;
        }
#endif

#if SILVERLIGHT
        private CaptureSource _captureSource;
        private MyAudioSink _audioSink;
        private Brush Green = new SolidColorBrush(Color.FromArgb(255, 0, 255, 0));
        private Brush Red = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
        private Brush Black = new SolidColorBrush(Color.FromArgb(255, 0, 0, 0));
        private void buttonStart_Click(object sender, RoutedEventArgs e)
        {
            dir = new util();
            if (CaptureDeviceConfiguration.RequestDeviceAccess())
            {
                buttonStart.Visibility = System.Windows.Visibility.Collapsed;
                comboDevices.Visibility = System.Windows.Visibility.Collapsed;
                mem_size = 30000;
                mem_l = new float[mem_size];
                mem_r = new float[mem_size];
                _captureSource = new CaptureSource();
                _captureSource.AudioCaptureDevice.AudioFrameSize = 50;
                _captureSource.VideoCaptureDevice = null;
                foreach (AudioFormat _format in _captureSource.AudioCaptureDevice.SupportedFormats)
                {
                    if ((_format.BitsPerSample == 16) && (_format.Channels == 2) && 
                        //(_format.SamplesPerSecond == 44100))
                        (_format.SamplesPerSecond == 22050))
                    {
                        _captureSource.AudioCaptureDevice.DesiredFormat = _format;
                    }
                }
                _audioSink = new MyAudioSink();
                _audioSink.CaptureSource = _captureSource;
                _audioSink.DataAvailable += new EventHandler<WaveInEventArgs>(waveIn_DataAvailable);
                _captureSource.Start();
                AudioFormat _fmt = _captureSource.AudioCaptureDevice.DesiredFormat;
                labelWaveformat.Text = _fmt.SamplesPerSecond.ToString();
                labelChannel.Text = _fmt.Channels.ToString();
                labelBitsPerSample.Text = _fmt.BitsPerSample.ToString();
                run = true;
            }
        }
#else
        private void buttonStart_Click(object sender, RoutedEventArgs e)
        {
            if (waveIn == null)
            {
                if (wasapi==false)
                {
                    waveIn = new WaveIn();
                    waveIn.WaveFormat = new WaveFormat(8000, 1);
                    labelWasapi.Visibility = Visibility.Hidden;
                }
                else
                {
                    waveIn = new WaveIn();
                    waveIn = new WasapiCapture((MMDevice)comboDevices.SelectedItem);
                    waveIn.WaveFormat = new WaveFormat(44100, 2);
                    labelWasapi.Visibility = Visibility.Visible;
                }

                if(waveIn.WaveFormat==null)
                {
                    MessageBox.Show("Could not open audio device");
                    return;
                }
                _samplerate = waveIn.WaveFormat.SampleRate;
                labelWaveformat.Text = waveIn.WaveFormat.SampleRate.ToString();
                labelChannel.Text = waveIn.WaveFormat.Channels.ToString();
                labelBitsPerSample.Text = waveIn.WaveFormat.BitsPerSample.ToString();

                waveIn.DataAvailable += new EventHandler<WaveInEventArgs>(waveIn_DataAvailable);
                waveIn.RecordingStopped += new EventHandler(waveIn_RecordingStopped);
                waveIn.StartRecording();
                buttonStart.IsEnabled = false;
            }
        }
#endif

#if !SILVERLIGHT
        void waveIn_RecordingStopped(object sender, EventArgs e)
        {
            waveIn.Dispose();
            waveIn = null;
            writer.Close();
            writer = null;

            Dispatcher.Invoke(DispatcherPriority.Normal, ((ThreadStart)delegate()
            {
                buttonStart.IsEnabled = true;
            }));
        }
#endif


        private int seq_cnt = 0;
        private int seq_cnt_l = 0;
        private int seq_cnt_r = 0;
        public  int seq_start_l = 0;
        public int seq_start_r = 0;
        private bool inhibit_left = false;
        private bool inhibit_right = false;
        private int off_cnt_l = 50;
        private int off_cnt_r = 200;
        void waveIn_DataAvailable(object sender, WaveInEventArgs e)
        {

            if (run == false) return;
            else
            {
#if SILVERLIGHT
                if (run_cnt == 0)
                    Dispatcher.BeginInvoke( () =>labelRun.Foreground = Green);
                else if (run_cnt == 50)
                    Dispatcher.BeginInvoke(() => labelRun.Foreground = Black);
#else
                if (run_cnt==0)
                     Dispatcher.Invoke(DispatcherPriority.Normal, ((ThreadStart)delegate()
                    { labelRun.Background = Brushes.Green;}));
                else if (run_cnt == 50) 
                    Dispatcher.Invoke(DispatcherPriority.Normal, ((ThreadStart)delegate()
                   { labelRun.Background = Brushes.Transparent; }));
#endif
                run_cnt++;
                if (run_cnt >= 100) run_cnt = 0;
            }

            byte[] buffer = e.Buffer;
            int bytesRecorded = e.BytesRecorded;
            _samplenumber = bytesRecorded;

            for (int index = 0; index < e.BytesRecorded; index += 4)
            {
                short sample_left = (short)((buffer[index + 1] << 8) | buffer[index + 0]);
                short sample_right = (short)((buffer[index + 3] << 8) | buffer[index + 2]);

                float sample32_left = sample_left / 32768f;
                float sample32_right = sample_right / 32768f;

#if SILVERLIGHT
                Dispatcher.BeginInvoke(() => progressBarLeft.Value = sample32_left);
                Dispatcher.BeginInvoke(() => progressBarRight.Value = sample32_right);
#else
                if (index== 0)
                {
                    Dispatcher.Invoke(DispatcherPriority.Normal, ((ThreadStart)delegate()
                    {
                        progressBarLeft.Value = sample32_left;
                        progressBarRight.Value = sample32_right;
                    }));
                }
#endif
                if (_enable_left)
                {
                    if (trigger_left == false)
                    {
                        if ((sample32_left > left_in) && !inhibit_left)
                        {
                            trigger_left = true;
                            seq_cnt_l = 0;
                            if(trigger_right==false) seq_cnt = 0;
                            seq_start_l = seq_cnt;
#if SILVERLIGHT
                            Dispatcher.BeginInvoke(() => labelLeftTrigger.Foreground = Red);
#else
                            Dispatcher.Invoke(DispatcherPriority.Normal, ((ThreadStart)delegate()
                            {
                                labelLeftTrigger.Background = Brushes.Red;
                            }));
#endif
                        }
                    }
                    else
                    {
                        if ((sample32_left > -left_out) && (sample32_left < left_out))
                        {
                            off_cnt_left++;
                            if (off_cnt_left > off_cnt_l)
                            {
                                trigger_left = false;
                                if (trigger_right == false) DataWrite(seq_cnt, seq_start_l, seq_cnt_l, seq_start_r, seq_cnt_r);
                                else inhibit_left = true;
#if SILVERLIGHT
                                Dispatcher.BeginInvoke(() => labelLeftTrigger.Foreground = Black);
#else
                                Dispatcher.Invoke(DispatcherPriority.Normal, ((ThreadStart)delegate()
                                {
                                    labelLeftTrigger.Background = Brushes.Transparent;
                                }));
#endif
                            }
                        }
                        else off_cnt_left = 0;
                    }
                }

                if (_enable_right)
                {
                    if (trigger_right == false)
                    {
                        if ((sample32_right > right_in) && !inhibit_right)
                        {
                            trigger_right = true;
                            seq_cnt_r = 0;
                            if (trigger_left == false) seq_cnt = 0;
                            seq_start_r = seq_cnt;
#if SILVERLIGHT
                            Dispatcher.BeginInvoke(() => labelRightTrigger.Foreground = Red);
#else
                            Dispatcher.Invoke(DispatcherPriority.Normal, ((ThreadStart)delegate()
                            {
                                labelRightTrigger.Background = Brushes.Red;
                            }));
#endif
                        }
                    }
                    else
                    {
                        if ((sample32_right > -right_out) && (sample32_right < right_out))
                        {
                            off_cnt_right++;
                            if (off_cnt_right > off_cnt_r)
                            {
                                trigger_right = false;
                                if (trigger_left == false) DataWrite(seq_cnt, seq_start_l, seq_cnt_l, seq_start_r, seq_cnt_r);
                                else inhibit_right = true;
#if SILVERLIGHT
                                Dispatcher.BeginInvoke(() => labelRightTrigger.Foreground = Black);
#else
                                Dispatcher.Invoke(DispatcherPriority.Normal, ((ThreadStart)delegate()
                                {
                                    labelRightTrigger.Background = Brushes.Transparent;
                                }));
#endif
                            }
                        }
                        else off_cnt_right = 0;
                    }
                }

                if (trigger_left)
                {
                    if (mem_size > seq_cnt_l)
                    {
                        mem_l[seq_cnt_l] = sample32_left;
                        seq_cnt_l++;
                    }
                    else OverMemory();
                }
                if (trigger_right)
                {
                    if (mem_size > seq_cnt_r)
                    {
                        mem_r[seq_cnt_r] = sample32_right;
                        seq_cnt_r++;
                    }
                    else OverMemory();
                } 
                if((trigger_left==true) || (trigger_right==true)) seq_cnt++;
            }
        }

        private void OverMemory()
        {
            trigger_left = false;
            trigger_right = false;
            inhibit_left = false;
            inhibit_right = false;

            DataWrite(seq_cnt, seq_start_l, seq_cnt_l, seq_start_r, seq_cnt_r);

#if SILVERLIGHT
            Dispatcher.BeginInvoke(() => labelRightTrigger.Foreground = Black);
            Dispatcher.BeginInvoke(() => labelLeftTrigger.Foreground = Black);
#else
            Dispatcher.Invoke(DispatcherPriority.Normal, ((ThreadStart)delegate()
            {
                labelLeftTrigger.Background = Brushes.Transparent;
            }));

            Dispatcher.Invoke(DispatcherPriority.Normal, ((ThreadStart)delegate()
            {
                labelRightTrigger.Background = Brushes.Transparent;
            }));
#endif
        }

        private void DataWrite(int master, int start_l,int cnt_l, int start_r,int cnt_r)
        {
            _buffer_no++; 
            if (_buffer_no > BufferCnt) _buffer_no = 1;

            if (noize_reject != 0)
            {
                if (_enable_left) mem_l = filter_noize(mem_l, cnt_l, noize_reject);
                if (_enable_right) mem_r = filter_noize(mem_r, cnt_r, noize_reject);
            }

            switch (filter_index)
            {
                case 1:
                    if (_enable_left) mem_l = filter_mean5(mem_l, cnt_l);
                    if (_enable_right) mem_r = filter_mean5(mem_r, cnt_r);
                    break;
                case 2:
                    if (_enable_left) mem_l = filter_gauss(mem_l, cnt_l);
                    if (_enable_right) mem_r = filter_gauss(mem_r, cnt_r);
                    if (_enable_left) mem_l = filter_gauss(mem_l, cnt_l);
                    if (_enable_right) mem_r = filter_gauss(mem_r, cnt_r);
                    if (_enable_left) mem_l = filter_gauss(mem_l, cnt_l);
                    if (_enable_right) mem_r = filter_gauss(mem_r, cnt_r);
                    break;
                case 3:
                    if (_enable_left) mem_l = filter_BiQuad(2500.0f, mem_l, cnt_l);
                    if (_enable_right) mem_r = filter_BiQuad(1000.0f,mem_r, cnt_r);
                    break;
            }

            try
            {
                using (var csv_writer = new StreamWriter(dir.BaseDir + "sampling" + _buffer_no.ToString() + ".csv"))
                {                    
                    if (_enable_left && _enable_right)
                    {
                        csv_writer.WriteLine("Waveform,CH1,Ch2");
                        for (int i = 0; i < master; i++)
                        {
                            if ((start_l <= i) && (start_r <= i))
                                csv_writer.WriteLine((i * axis_y_mux).ToString() + "," + (mem_l[i]*axis_x_mux).ToString() + "," + (mem_r[i]*axis_x_mux).ToString());
                            else if (start_r <= i)
                                csv_writer.WriteLine((i * axis_y_mux).ToString() + "," + "0" + "," + (mem_r[i] * axis_x_mux).ToString());
                            else if (start_l <= i)
                                csv_writer.WriteLine((i * axis_y_mux).ToString() + "," + (mem_l[i] * axis_x_mux).ToString() + "," + "0");
                            else
                                csv_writer.WriteLine((i * axis_y_mux).ToString() + "," + "0" + "," + "0");
                        }
                    }
                    else if (_enable_left)
                    {
                        csv_writer.WriteLine("Waveform,CH1");
                        for (int i = 0; i < master; i++)
                                csv_writer.WriteLine(i.ToString() + "," + mem_l[i].ToString());
                    }
                    else if (_enable_right)
                    {
                        csv_writer.WriteLine("Waveform,Ch2");
                        for (int i = 0; i < master; i++)
                            csv_writer.WriteLine(i.ToString() +  "," + mem_r[i].ToString());
                    }
                    csv_writer.Close();
                }

                if (_enable_left)
                {
                    using (var csv_writer_left = new StreamWriter(dir.BaseDir + "sample_l" + _buffer_no.ToString() + ".csv"))
                    {
                        for (int i = 0; i < cnt_l; i++)
                            csv_writer_left.WriteLine(mem_l[i].ToString());
                        csv_writer_left.Close();
                    }
                }

                if (_enable_right)
                {
                    using (var csv_writer_right = new StreamWriter(dir.BaseDir +  "sample_r" + _buffer_no.ToString() + ".csv"))
                    {
                        for (int i = 0; i < cnt_r; i++)
                            csv_writer_right.WriteLine(mem_r[i].ToString());
                        csv_writer_right.Close();
                    }
                }
            }
            catch
            {
                inhibit_left = false;
                inhibit_right = false;
                return;
            }
            inhibit_left = false;
            inhibit_right = false;

            _captured = true;
        }

        private float[] filter_noize(float[] src, int len, float noize)
        {
            int size = src.Length;
            float[] dst = new float[size];
            for (int i = 0; i < len; i++) dst[i] = (Math.Abs(src[i]) < noize) ? 0 : src[i];

            return dst;
        }

        private float[] filter_mean3(float[] src, int len)
        {
            int size = src.Length;
            float[] dst = new float[size];
            for (int i = 0; i < len; i++)
            {
                if (i == 0) dst[i] = (src[i] + src[i] + src[i + 1]) / 3;
                else if(i==len-1) dst[i] = (src[i-1] + src[i] + src[i])/3;
                else dst[i] = (src[i-1] + src[i] + src[i+1])/3;
            }

            return dst;
        }

        private float[] filter_mean5(float[] src, int len)
        {
            int size = src.Length;
            float[] dst = new float[size];
            for (int i = 0; i < len; i++)
            {
                if (i == 0) dst[i] = (src[i] + src[i] + src[i] + src[i + 1] + src[i + 2]) / 5;
                else if (i == 1) dst[i] = (src[i-1] + src[i - 1] + src[i] + src[i + 1] + src[i + 2]) / 5;
                else if (i == len - 2) dst[i] = (src[i - 2] + src[i - 1] + src[i] + src[i + 1] + src[i + 1]) / 5;
                else if (i == len - 1) dst[i] = (src[i - 2] + src[i - 1] + src[i] + src[i] + src[i]) / 5;
                else dst[i] = (src[i - 2] + src[i - 1] + src[i] + src[i + 1] + src[i + 2]) / 5;
            }

            return dst;
        }
        float[] GK = new float[] { .0625f, .25f, .375f, .25f, .0625f };
        private float[] filter_gauss(float[] src, int len)
        {
            int size = src.Length;
            float[] dst = new float[size];
            for (int i = 0; i < len; i++)
            {
                if (i == 0) dst[i] = src[i]*GK[0] + src[i]*GK[1] + src[i]*GK[2] + src[i + 1]*GK[3] + src[i + 2]*GK[4];
                else if (i == 1) dst[i] = src[i - 1]*GK[0] + src[i - 1]*GK[1] + src[i]*GK[2] + src[i + 1]*GK[3] + src[i + 2]*GK[4];
                else if (i == len - 2) dst[i] = src[i - 2]*GK[0] + src[i - 1]*GK[1] + src[i]*GK[2] + src[i + 1]*GK[3] + src[i + 1]*GK[4];
                else if (i == len - 1) dst[i] = src[i - 2]*GK[0] + src[i - 1]*GK[1] + src[i]*GK[2] + src[i]*GK[3] + src[i]*GK[4];
                else dst[i] = src[i - 2]*GK[0]+ src[i - 1]*GK[1] + src[i]*GK[2] + src[i + 1]*GK[3] + src[i + 2]*GK[4];
            }

            return dst;
        }

        private float[] filter_BiQuad(float freq, float[] src, int len)
        {
            float[] dst = new float[src.Length];

#if !SILVERLIGHT
            NAudio.Dsp.BiQuadFilter filter =
                NAudio.Dsp.BiQuadFilter.LowPassFilter((float)_samplerate,freq,0.5f);
                //NAudio.Dsp.BiQuadFilter.BandPassFilterConstantPeakGain((float)SampleRate,2000.0f,0.9f);
                //NAudio.Dsp.BiQuadFilter.BandPassFilterConstantSkirtGain((float)SampleRate, 2000.0f, 0.9f);
                //NAudio.Dsp.BiQuadFilter.LowShelf((float)SampleRate, 1000.0f, 1.0f,1.5f);
            filter.Transform(src, ref dst);
#endif

            return dst;
        }

        private void buttonStop_Click(object sender, RoutedEventArgs e)
        {
#if !SILVERLIGHT
            if (waveIn != null)
            {
                waveIn.StopRecording();
            }
#endif
        }

        private void textBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (textBoxLeftTrigger == null) return;
            if (textBoxLeftOff == null) return;
            if (textBoxRightTrigger == null) return;
            if (textBoxRightOff == null) return;
            if (textBoxNoiseReduction == null) return;
            if (checkBoxNoiseReduction == null) return;
            if (textBoxBufferCnt == null) return;
            if (textBoxXAxisName == null) return;
            if (textBoxYAxisName == null) return;
            if (textBoxXAxisMultiple == null) return;
            if (textBoxYAxisMultiple == null) return;

            _name_x = textBoxXAxisName.Text;
            _name_y = textBoxYAxisName.Text;

            try
            {
                axis_x_mux = double.Parse(textBoxXAxisMultiple.Text);
            }
            catch { textBoxXAxisMultiple.Text = "1.0"; };
            try
            {
                axis_y_mux = double.Parse(textBoxYAxisMultiple.Text);
            }
            catch { textBoxYAxisMultiple.Text = "1.0"; };
            try
            {
                left_in = float.Parse(textBoxLeftTrigger.Text);
            }
            catch { textBoxLeftTrigger.Text = "0.25"; };
            try
            {
                left_out = float.Parse(textBoxLeftOff.Text);
            }
            catch { textBoxLeftOff.Text = "0.1"; };
            try
            {
                right_in = float.Parse(textBoxRightTrigger.Text);
            }
            catch { textBoxRightTrigger.Text = "0.25"; };
            try
            {
                right_out = float.Parse(textBoxRightOff.Text);
            }
            catch { textBoxRightOff.Text = "0.1"; };
            try
            {
                if (checkBoxNoiseReduction.IsChecked == false) noize_reject = 0;
                else noize_reject = float.Parse(textBoxNoiseReduction.Text);
            }
            catch { textBoxNoiseReduction.Text = "0.0"; };
            try
            {
                BufferCnt = int.Parse(textBoxBufferCnt.Text);
            }
            catch { textBoxBufferCnt.Text = "100"; };
        }

        private void checkBoxNoiseReduction_Checked(object sender, RoutedEventArgs e)
        {
            if (checkBoxNoiseReduction == null) return;
            if (textBoxNoiseReduction == null) return;
            
            if (checkBoxNoiseReduction.IsChecked == false) noize_reject = 0;
            else
            {
                try
                {
                    noize_reject = float.Parse(textBoxNoiseReduction.Text);
                }
                catch { textBoxNoiseReduction.Text = "0.1"; };
            }
        }

        private void textBoxMemory_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (textBoxMemory == null) return;
            mem_size = 30000;
            try
            {
                mem_size = int.Parse(textBoxMemory.Text);
            }
            catch { textBoxMemory.Text = "30000"; };

            mem_l = new float[mem_size];
            mem_r = new float[mem_size];
        }

        private void comboBoxFilter_Loaded(object sender, RoutedEventArgs e)
        {
            comboBoxFilter.SelectedIndex = 2;
        }

        private void comboBoxFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboBoxFilter == null) return;
            filter_index = comboBoxFilter.SelectedIndex;
        }

        private void radioButtonRun_Checked(object sender, RoutedEventArgs e)
        {
            if (radioButtonRunOn == null) return;
            if (radioButtonRunOff == null) return;
#if !SILVERLIGHT
            if (radioButtonRunOn.IsChecked == true) run = true;
            else
            {
                run = false;
                labelRun.Background = Brushes.Transparent;
            }
#endif
        }

        private void checkBoxChEnable(object sender, RoutedEventArgs e)
        {
            if (checkBoxLeft == null) return;
            if (checkBoxRight == null) return;

            if (checkBoxLeft.IsChecked == true) _enable_left = true;
            else _enable_left = false;
            if (checkBoxRight.IsChecked == true) _enable_right = true;
            else _enable_right = false;

        }
    }
}
